<?php

namespace Tbf\Bundle\AlipayBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Tbf\Component\Arrays\ArrayFunction;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class TbfAlipayExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $err = ArrayFunction::checkParameterExist($config,array('seller_email','app_key','app_secret'));
        if ($err!==null){
            throw new \Exception(sprintf('You need config tbf_alipay to use it. Reason: %s',$err));
        }
        $container->setParameter('tbf_alipay.seller_id',$config['seller_id']);
        $container->setParameter('tbf_alipay.seller_account_name',$config['seller_account_name']);
        $container->setParameter('tbf_alipay.seller_email',$config['seller_email']);
        $container->setParameter('tbf_alipay.app_key',$config['app_key']);
        $container->setParameter('tbf_alipay.app_secret',$config['app_secret']);
        if (!empty($config['seller_id'])){
            $container->getDefinition('tbf_alipay.config')->addMethodCall(
                'setSellerId',array($config['seller_id'])
            );
        }
        if (!empty($config['seller_account_name'])){
            $container->getDefinition('tbf_alipay.config')->addMethodCall(
                'setSellerAccountName',array($config['seller_account_name'])
            );
        }
        if (!empty($config['seller_email'])){
            $container->getDefinition('tbf_alipay.config')->addMethodCall(
                'setSellerEmail',array($config['seller_email'])
            );
        }
    }
}
